package com.vichat.gps.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.util.LocationUtil;
import com.vichat.core.dao.BaseDaoI;
import com.vichat.gps.entity.AlarmLog;
import com.vichat.gps.entity.LocationData;
import com.vichat.gps.entity.LocationDataLog;
import com.vichat.gps.service.IGpsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 82116 on 2018/2/24.
 */
@Service("gpsService")
public class GpsServiceImpl implements IGpsService {
    @Autowired
    private BaseDaoI<LocationData> locationDataDao;
    @Autowired
    private BaseDaoI<LocationDataLog> locationDataLogDao;


    private static Logger logger = LoggerFactory.getLogger(GpsServiceImpl.class);

    /**
     * 保存定位信息
     *
     * @param locData
     * @throws Exception
     */
    public void saveLocationData(LocationData locData) throws Exception {
        String jsonStr = RedisHelper.getLocationData(String.valueOf(locData.getUid()));
        //logger.info(jsonStr);
        if (StringUtils.isNotBlank(jsonStr)) {
            LocationData locationDataFDB = JSONObject.parseObject(jsonStr, LocationData.class);
            //logger.info(locationDataFDB.getLocTime().longValue() + ":" + locData.getLocTime().longValue());
            if (locationDataFDB.getLocTime().longValue() != locData.getLocTime().longValue()) {
                saveLocation(locData);
                RedisHelper.setLocationData(String.valueOf(locData.getUid()), JSONObject.toJSONString(locData));
                saveLocationLog(locData);
            }
        } else {
            saveLocation(locData);
            RedisHelper.setLocationData(String.valueOf(locData.getUid()), JSONObject.toJSONString(locData));
            saveLocationLog(locData);
        }
    }

    /**
     * gps定位插入sql
     *
     * @param data
     * @return
     */
    private void saveLocation(LocationData data) {
        String tablename = LocationUtil.getLocationDataTableName(new Date(data.getLocTime()));
        StringBuilder sql = new StringBuilder();
        sql.append("insert into ").append(tablename);
        sql.append("(uid,latitude,longitude,address,pre_cision,speed,loc_type,loc_time,sumTime,party_id,org_id,org_code)");
        sql.append(" values (").append(data.getUid()).append(",'");
        sql.append(data.getLatitude()).append("','").append(data.getLongitude()).append("','");
        sql.append(data.getAddress()).append("','").append(data.getPreCision()).append("','");
        sql.append(data.getSpeed()).append("',").append(data.getLocType()).append(",");
        sql.append(data.getLocTime()).append(",").append(data.getSumtime()).append(",").append(data.getPartyId()).append(",");
        sql.append(data.getOrgId()).append(",'").append(data.getOrgCode()).append("')");
        locationDataDao.executeSql(sql.toString());
    }
    private void saveLocationLog(LocationData data) {
        StringBuilder sql = new StringBuilder();
        sql.append("REPLACE into gpsdb.location_data_log ");
        sql.append("(uid,latitude,longitude,address,pre_cision,speed,loc_type,loc_time,sumTime,party_id,org_id,org_code)");
        sql.append(" values (").append(data.getUid()).append(",'");
        sql.append(data.getLatitude()).append("','").append(data.getLongitude()).append("','");
        sql.append(data.getAddress()).append("','").append(data.getPreCision()).append("','");
        sql.append(data.getSpeed()).append("',").append(data.getLocType()).append(",");
        sql.append(data.getLocTime()).append(",").append(data.getSumtime()).append(",").append(data.getPartyId()).append(",");
        sql.append(data.getOrgId()).append(",'").append(data.getOrgCode()).append("')");
        locationDataDao.executeSql(sql.toString());
    }
    /**
     * gps定位插入sql
     *
     * @param datas
     * @return
     */
    public void saveBatchLocation(List<LocationData> datas ) {
        String tablename = LocationUtil.getLocationDataTableName(new Date());
        StringBuilder sqlLocationData = new StringBuilder();
        StringBuilder body = new StringBuilder();
        sqlLocationData.append("insert into ").append(tablename);
        sqlLocationData.append("(uid,latitude,longitude,address");
        sqlLocationData.append(",pre_cision,speed,loc_type,loc_time,sumTime,party_id,org_id,org_code) values");


        StringBuilder sqlLocationDataLog = new StringBuilder();
        sqlLocationDataLog.append("REPLACE into gpsdb.location_data_log ");
        sqlLocationDataLog.append("(uid,latitude,longitude,address,pre_cision,speed,loc_type,loc_time,sumTime,party_id,org_id,org_code) values");
        for (int i=0;i<datas.size();i++) {
            LocationData data = datas.get(i);
            body.append("(").append(data.getUid()).append(",'");
            body.append(data.getLatitude()).append("','").append(data.getLongitude()).append("','");
            body.append(data.getAddress()).append("','").append(data.getPreCision()).append("','");
            body.append(data.getSpeed()).append("',").append(data.getLocType()).append(",");
            body.append(data.getLocTime()).append(",").append(data.getSumtime()).append(",").append(data.getPartyId()).append(",");
            body.append(data.getOrgId()).append(",'").append(data.getOrgCode()).append("')");
            if(i == datas.size()-1){
                body.append(";");
            }else{
                body.append(",");
            }
        }
        sqlLocationData.append(body);
        sqlLocationDataLog.append(body);
        logger.info(sqlLocationData.toString());
        logger.info(sqlLocationDataLog.toString());
        locationDataDao.executeSql(sqlLocationData.toString());
        locationDataDao.executeSql(sqlLocationDataLog.toString());
    }

    /**
     * 获取所有人员当天定位信息
     *
     * @param queryBean
     * @return
     * @throws Exception
     */
    public List<LocationDataLog> queryLocationDatas(LocationData queryBean, Date startDate, Date endDate) throws Exception {
        HashMap params = new HashMap();
        String sql = "select a.* from gpsdb.location_data_log a,userdb.user_basic b  where  a.party_Id=:partyId  and  a.uid = b.uid and b.state = 1 ";
        if (StringUtils.isNotEmpty(queryBean.getOrgCode())) {
            sql += "and a.org_code like :orgCode";
            params.put("orgCode", queryBean.getOrgCode() + "%");
        }
        if (startDate != null) {
            sql += "and a.loc_time > :startDate";
            params.put("startDate", startDate.getTime());
        }
        if (endDate != null) {
            sql += "and a.loc_time < :endDate";
            params.put("endDate", endDate.getTime());
        }
        params.put("partyId", queryBean.getPartyId());

        return locationDataLogDao.findEntityBySql(sql.toString(), params,LocationDataLog.class);
    }

    /**
     * 获取人员当天定位信息
     *
     * @param uid
     * @return
     * @throws Exception
     */
    public List<LocationData> getLocationDatasByUid(long uid, String date) throws Exception {
        HashMap params = new HashMap();
        StringBuilder sql = new StringBuilder();
        String tablename;
        if (StringUtils.isEmpty(date)) {
            tablename = LocationUtil.getLocationDataTableName(new Date());
        } else {
            tablename = LocationUtil.getLocationDataTableName(date);
        }
        sql.append("select * from ").append(tablename).append(" where ");
        sql.append(" uid=:uid");
        sql.append(" order by loc_time desc");
        params.put("uid", uid);
        List<LocationData> locationDatas = locationDataDao.findEntityBySql(sql.toString(), params, LocationData.class);

        return locationDatas;
    }


}
